package com.ican.action.user;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ican.common.BusinessException;
import com.ican.common.SystemConstants;
import com.ican.domain.user.Resources;
import com.ican.domain.user.User;
import com.ican.service.user.ResourcesService;
import com.ican.service.user.UserService;
import com.ican.util.ContextUtils;
import com.opensymphony.xwork2.ActionSupport;

@Results({@Result(name="login", location="/login.jsp"),@Result(name="main", location="/common/main.jsp")})
public class LoginAction extends ActionSupport {
    
    private static final long serialVersionUID = -7555806386280429294L;
    private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);
    
    private UserService userService;
    private ResourcesService resourcesService;
    private User user;
    
    public String login(){
        try{
            if(userService.getLoginUserFromSession() != null){
                return loadZtreeContent();
            }
            if(user == null){
                return "login";
            }   
            user = userService.findUserByNameAndPw(user.getName(), user.getPassword());
            if(user == null || user.getId() == null){
                return "login";
            }
            user.setPassword(null);
            ContextUtils.getSessionMap().put(SystemConstants.KEY_USER_SESSION, user);
            return loadZtreeContent();
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
            return "login";
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
            return "login";
        }
    }
    
    public String loginOut(){
        try{
            ContextUtils.getSessionMap().remove(SystemConstants.KEY_USER_SESSION);
            ContextUtils.getSessionMap().remove(SystemConstants.KEY_MENU_TREE);
            ContextUtils.getSession().invalidate();
            return "login";
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
            return "login";
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
            return "login";
        }
    }
    
    private String loadZtreeContent(){
        user = userService.getLoginUserFromSession();
        List<Resources> rs = resourcesService.findAllResourceByUserId(user.getId());
        StringBuffer sb = new StringBuffer();
        if(rs != null){
            List<Integer> rids = new ArrayList<Integer>();
            sb.append("[");
            Resources r = null;
            for(int i = 0; i < rs.size(); i++){
                r = rs.get(i);
                if(!rids.contains(r.getId())){
                    sb.append("{id:" + r.getId().toString() + ",");
                    if(r.getPid() == null){
                        sb.append("pId:0,");
                    }else{
                        sb.append("pId:" + r.getPid().intValue() + ",");
                    }
                    sb.append("name:\"" + r.getName() + "\",");
                    if(r.getUrl() != null){
                        sb.append("fromAction:\"" + ContextUtils.getContextPath() + r.getUrl() + "\"}");
                    }else{
                        sb.append("fromAction:}");
                    }
                    if(i < rs.size() - 1){
                        sb.append(",");
                    }
                    rids.add(r.getId());
                }
            }
            sb.append("]");
        }
        ContextUtils.getSessionMap().put(SystemConstants.KEY_MENU_TREE, sb.toString());
        return "main";
    }

    @Resource
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @Resource
    public void setResourcesService(ResourcesService resourcesService) {
        this.resourcesService = resourcesService;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}
